﻿using Qy.Common;
using Qy.Models;
using Qy.Repository;
using PetaPoco;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Qy.Service;
[AppService]
public class UserService
{
    private readonly UserRepository _adminUserRepository;
    private readonly ICacheManager _cacheManager;
    private readonly string cacheKey, cacheListAll;
    private readonly UserDeptService _adminUserDeptService;
    public UserService(UserRepository adminUserRepository, ICacheManager cacheManager, UserDeptService adminUserDeptService)
    {
        _adminUserRepository = adminUserRepository;
        _cacheManager = cacheManager;
        cacheKey = CacheConst.CACHE_KEY_USER;
        cacheListAll = cacheKey + "all";
        _adminUserDeptService = adminUserDeptService;
    }

    public async Task<User> CheckUorP(string username, string password)
    {
        return await _adminUserRepository.CheckUorP(username, MD5Utility.MD5Encrypt32(password).ToLower());
    }

    public async Task<List<User>> GetUserAllListAsync()
    {
        List<User> adminUsers = _cacheManager.Get<List<User>>(cacheListAll);
        if (adminUsers == null)
        {
            adminUsers = _cacheManager.Get<List<User>>(cacheListAll);
            return await _adminUserRepository.GetAllListAsync("Id asc");
        }
        return adminUsers;
    }


    /// <summary>
    /// 获取一条用户信息无缓存
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<User> GetNoCacheAsync(int id)
    {
        return await _adminUserRepository.GetAsync(id);
    }

    /// <summary>
    /// 获取一条用户信息并缓存
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<ViewUser> GetAsync(int id)
    {
        ViewUser adminUser = _cacheManager.Get<ViewUser>(cacheKey + id);
        if (adminUser == null)
        {
            adminUser = await _adminUserRepository.GetUserInfoAsync(id);
            _cacheManager.Set(cacheKey + id, adminUser, TimeSpan.FromDays(31));
        }
        return adminUser;
    }
    /// <summary>
    /// 更新登录信息
    /// </summary>
    /// <param name="userId"></param>
    /// <param name="ip"></param>
    public async void UpdateLoginInfoAsync(int userId, string ip)
    {
        User adminUser = await GetNoCacheAsync(userId);
        adminUser.Logintime = DateTime.Now;
        adminUser.Loginip = ip;
        try
        {
            await _adminUserRepository.UpdateAsync(adminUser);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }

    }


    public async Task<Page<ViewUser>> GetPageListAsync(UserQuery query, int gid)
    {
        return await _adminUserRepository.GetPageListAsync(query, gid);
    }
    public async Task<List<UserIdAndName>> GetNameAsync(int userId, string name = null)
    {
        return await _adminUserRepository.GetNameAsync(userId, name);
    }


    public async Task<bool> GetByUsernameAsync(string username)
    {
        return await _adminUserRepository.GetByUsernameAsync(username);
    }

    public virtual async Task<object> InsertAsync(User user)
    {
        _cacheManager.Remove(cacheListAll);
        return await _adminUserRepository.InsertAsync(user);
    }

    public async Task<int> UpdateAsync(EditUser user)
    {
        User adminUser = await GetNoCacheAsync(user.Id);
        if (adminUser == null)
            return -1;

        //return Json(new { status = 0, msg = "请勿非法提交 Id:" + user.Id });

        if (user.Username != adminUser.Username && await GetByUsernameAsync(user.Username) == false)
            return -2;
        // Json(new { status = 0, msg = "该用户名已存在，请重新输入 Id:" + user.Id });


        adminUser.DeptId = user.DeptId;
        adminUser.PostId = user.PostId;
        adminUser.Gid = user.Gid;
        adminUser.Username = user.Username;
        adminUser.Nickname = user.Nickname;
        adminUser.Status = user.Status;

        if (!string.IsNullOrEmpty(user.Password))
        {
            adminUser.Password = MD5Utility.MD5Encrypt32(user.Password).ToLower();
        }

        if (0 < await _adminUserRepository.UpdateAsync(adminUser))
        {
            _cacheManager.Remove(cacheListAll);
            _cacheManager.Remove(cacheKey + user.Id);
            return 1;
        }
        else
        {
            return 0;//写入数据库失败
        }
    }

    public async Task<int> ChStatusUpdateAsync(EditUserStatus user)
    {
        User adminUser = await GetNoCacheAsync(user.Id);
        adminUser.Status = user.Status;

        if (0 < await _adminUserRepository.UpdateAsync(adminUser))
        {
            _cacheManager.Remove(cacheListAll);
            _cacheManager.Remove(cacheKey + user.Id);
            return 1;
        }
        else
        {
            return 0;
        }
    }

    public async Task<int> EditUserInfoUpdateAsync(EditUser editUser, int userID)
    {
        User adminUser = await GetNoCacheAsync(userID);
        if (Extensions.IsNotEmpty(editUser.Password))
        {
            string oldPassWord = MD5Utility.MD5Encrypt32(editUser.OldPassword).ToLower();
            if (adminUser.Password != oldPassWord)
                return 0;
            adminUser.Password = MD5Utility.MD5Encrypt32(editUser.Password).ToLower();
        }

        adminUser.Nickname = editUser.Nickname;
        adminUser.Sex = editUser.Sex;
        adminUser.Avatar = editUser.Avatar;
        adminUser.Phone = editUser.Phone;

        _cacheManager.Remove(cacheListAll);
        _cacheManager.Remove(cacheKey + adminUser.Id);
        return await _adminUserRepository.UpdateAsync(adminUser);
    }


    public async Task<int> DeleteByPriKeyAsync(int id)
    {
        _cacheManager.Remove(cacheListAll);
        _cacheManager.Remove(cacheKey + id);
        return await _adminUserRepository.DeleteByPriKeyAsync(id);
    }

    #region  判断部门用户权限
    /// <summary>
    /// 查询当前部门用户ID列表
    /// </summary>
    /// <param name="deptId"></param>
    /// <returns></returns>
    private async Task<string> GetUserIds(int deptId)
    {
        List<User> all = await GetUserAllListAsync();
        List<User> userIds = all.Where(o => o.DeptId == deptId).ToList();
        List<int> ids = userIds.Select(o => o.Id).ToList();
        return string.Join(",", ids.ToArray());
    }
    /// <summary>
    /// 查询当前部门及子部门用户ID列表
    /// </summary>
    /// <param name="deptId"></param>
    /// <returns></returns>
    private async Task<string> GetUserAndSonDeptIds(int deptId)
    {
        List<User> userAll = await GetUserAllListAsync();
        List<int> uids = new();
        List<int> deptIds = await _adminUserDeptService.GetDeptAndSonIdsAsync(deptId);
        foreach (int did in deptIds)
        {
            List<User> userIds = userAll.Where(o => o.DeptId == did).ToList();
            List<int> ids = userIds.Select(o => o.Id).ToList();
            uids.AddRange(ids);
        }
        return string.Join(",", uids.ToArray());

    }
    /// <summary>
    /// 通过员工职务判断资源管理权限
    /// </summary>
    /// <param name="adminUser"></param>
    /// <returns></returns>
    public async Task<string> UserPostAsUids(UserInfo adminUser)
    {
        string uids;
        if (adminUser.Gid == 1 || adminUser.PostCode == UserPostConst.SUPREME)
            uids = null;//空为显示全部,超级管理员和部门最高领导
        else if (adminUser.PostCode == UserPostConst.MASTER || adminUser.PostCode == UserPostConst.DEPUTY)
            uids = await GetUserAndSonDeptIds(adminUser.DeptId);//显示自己部门及子部门员工所属资源
        else if (adminUser.PostCode == UserPostConst.WORKER)
            uids = await GetUserIds(adminUser.DeptId);//显示本级部门全部员工所属资源
        else
        {
            uids = "own"; //默认只显示自己的或者自定义的职务
                          //if (adminUser.PostCode == UserPostConst.OTHER)
                          //    uids = "own";
        }
        return uids;
    }
    #endregion
}

